Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

215
Visualizações
Vue/JS object order by date, except if an item has a "pinned" property

I have an object of newsfeed items like below.

[{'story_id':130,'pinned':0,....},{'story_id':131,'pinned':1,....},{'story_id':132,'pinned':0,....},{'story_id':133,'pinned':0,....}]

I need to primarily order the news stories by their story_id DESC. But if a story has the property 'pinned'=1 it needs to be first.

filtered_news_feed: function() {
    var list= _.orderBy(this.feed_items, ['story_id'],'desc');
    return list;
},

The above works, but how do I do pinned items first, then the rest? For some reason the below completely ignores the story_id

var list= _.orderBy(this.feed_items, ['pinned','story_id'],'desc');

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Using Array#sort:

const arr = [ {'story_id':130,'pinned':0}, {'story_id':131,'pinned':1}, {'story_id':132,'pinned':0}, {'story_id':133,'pinned':0} ];

const sorted = arr.sort(
  ({ story_id: storyIdA, pinned: pinnedA }, { story_id: storyIdB, pinned: pinnedB }) => 
    pinnedB - pinnedA || storyIdB - storyIdA
);

console.log(sorted);

about 4 years ago · Juan Pablo Isaza Relatório

0

You can achieve this results in many ways, one of them is:

filtered_news_feed: function() {
  const pinnedItems = this.feed_items.filter(item => item.pinned === 1);
  const normalItems = this.feed_items.filter(item => item.pinned === 0);

  return [
     ...pinnedItems,
     _.orderBy(normalItems, ['story_id'], 'desc')
  ];
}

First, separate pinned items from normal items. Then return merged array with pinned items at the beginning.

Note: I used modern features of ES here. You should compile it via babel or other tool.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda